let sendMemberId;
let acceptMemberId;
let sendAvatarUrl;
let acceptAvatarUrl;


// imgbox 图片点击放大
function imgbox() {
    $("div>a").imgbox({
        'speedIn': 500,  //设置放大速度
        'speedOut': 500, //设置缩小速度。
        'alignment': 'center', //位置-可能是自动或居中。 auto OR center.
        'overlayShow': true, //在imgBox下显示一个叠加层。
        'allowMultiple': false,  //允许打开多个imgBoxes。
        'autoScale': true,  //缩放图像以适合可用空间。
        'hideOnOverlayClick': true,// 单击叠加层时隐藏imgBox。
        'slideshow': false,   // 显示下一个/上一个控件。
        'easingIn': 'swing',         //设置放大动画的缓动效果。
        'easingOut': 'swing'     //设置缩小动画的宽松程度。
    });
}

//播放发送消息的铃声
function playSendMsgSound() {
    //获取音频播放对象
    var audio = new Audio("im/mp3/send.wav");
    audio.play();
}

//播放消息接受的铃声
function playReceiveMsgSound() {
    //获取音频播放对象
    var audio = new Audio("im/mp3/receive.mp3");
    audio.play();
}

// 加载会员信息
$.ajax({
    type: 'GET',
    url: 'getMember',
    dataType: 'json',
    success: function (data) {
        console.log(data)
        if (data.status == 100) {
            layer.open({
                content: '<span style="color: #f46266">你还没有登录哦!</span>'
                , btn: '我知道了'
                , shadeClose: false
                , yes: function (index) {
                    window.location.href = "login.html";
                }
            });

        } else {
            sendMemberId = data.data.memberId;
            sendAvatarUrl = data.data.avatarUrl
            buddyList.innerHTML = '';
            //传名字
            $(".userName").text(data.data.userName);
            //传头像
            $(".avatarUrl>img").attr("src", data.data.avatarUrl);

            CHAT.init();
        }
    }
});

//  好友列表渲染
const list = ({avatarUrl, userName, unreadMessageFriend, memberId}) => {
    return `<div class="chat-list-people" onclick="chatPage('${userName}','${avatarUrl}','${memberId}')">
                   <div>
                   <img src="${avatarUrl}" alt="${userName}"></div>
                   <div class="chat-name">
                       <p>${userName}</p>
                   </div>
                   <div class="message-num">${unreadMessageFriend > 0 ? unreadMessageFriend : ''}</div>
                 </div>`
}

//      发送信息
$("#chat-fasong").click(function () {
    console.log("sendMemberId：", sendMemberId)
    console.log("acceptMemberId：", acceptMemberId)
    var textContent = $(".div-textarea").html().replace(/[\n\r]/g, '<br>')
    if (textContent != "") {
        $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\">" + sendTime() + "</small> </div> " +
            "<div class=\"right\"> <div class=\"chat-message\"> " + textContent + " </div> " +
            "<div class=\"chat-avatars\"><img src=" + sendAvatarUrl + " alt=\"头像\" /></div> </div> </div>");
        //发送后清空输入框
        $(".div-textarea").html("");
        var chatMsg = {
            "sendMemberId": sendMemberId,
            "acceptMemberId": acceptMemberId,
            "msg": textContent,
        };
        var data = {
            "type": "SINGLE_SENDING",
            "chatMsg": chatMsg
        };
        // websocket 发送消息
        CHAT.chat(JSON.stringify(data))
        //聊天框默认最底部
        chatBottom();
    }

});

/**
 * 布局
 */
screenFuc();

function screenFuc() {
    var topHeight = $(".chatBox-head").innerHeight();//聊天头部高度
    //屏幕小于768px时候,布局change
    var winWidth = $(window).innerWidth();
    if (winWidth <= 768) {
        var totalHeight = $(window).height(); //页面整体高度
        $(".chatBox-info").css("height", totalHeight - topHeight);
        var infoHeight = $(".chatBox-info").innerHeight();//聊天头部以下高度
        //中间内容高度
        $(".chatBox-content").css("height", infoHeight - 46);
        $(".chatBox-content-demo").css("height", infoHeight - 46);

        $(".chatBox-list").css("height", totalHeight - topHeight);
        $(".chatBox-kuang").css("height", totalHeight - topHeight);
        $(".div-textarea").css("width", winWidth - 106);
    } else {
        $(".chatBox-info").css("height", 495);
        $(".chatBox-content").css("height", 448);
        $(".chatBox-content-demo").css("height", 448);
        $(".chatBox-list").css("height", 495);
        $(".chatBox-kuang").css("height", 495);
        $(".div-textarea").css("width", 230);
    }
}

(window.onresize = function () {
    screenFuc();
})();


// 总未读信息数量为空时
function unreadMessageFriend() {
    var totalNum = $(".chat-message-num").html();
    if (totalNum == "") {
        $(".chat-message-num").css("padding", 0);
    } else {
        $(".chat-message-num").css("padding", '');
    }
}

// 好友列表未读消息
function notMsg() {
    $(".message-num").each(function () {
        var wdNum = $(this).html();
        if (wdNum == "") {
            $(this).css("padding", 0);
        }
    });
}

//打开/关闭聊天框
$(".chatBtn").click(function () {
    $(".chatBox").toggle(10);
})
$(".chat-close").click(function () {
    $(".chatBox").toggle(10);
})

//返回列表
$(".chat-return").click(function () {
    $(".chatBox-head-one").toggle(1);
    $(".chatBox-head-two").toggle(1);
    $(".memberInfo").toggle(1);
    $(".chatBox-list").fadeToggle(1);
    $(".chatBox-kuang").fadeToggle(1);
});

//      发送表情
$("#chat-biaoqing").click(function () {
    $(".biaoqing-photo").toggle();
});
$(document).click(function () {
    $(".biaoqing-photo").css("display", "none");
});
$("#chat-biaoqing").click(function (event) {
    event.stopPropagation();//阻止事件
});

$(".emoji-picker-image").each(function () {
    $(this).click(function () {
        var textContent = $(this).parent().html();

        $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\">" + sendTime() + "</small> </div> " +
            "<div class=\"right\"> <div class=\"chat-message\"> " + textContent + " </div> " +
            "<div class=\"chat-avatars\"><img src=" + sendAvatarUrl + " alt=\"头像\" /></div> </div> </div>");
        var chatMsg = {
            "sendMemberId": sendMemberId,
            "acceptMemberId": acceptMemberId,
            "msg": textContent,
        };
        var data = {
            "type": "SINGLE_SENDING",
            "chatMsg": chatMsg
        };
        // websocket 发送消息
        CHAT.chat(JSON.stringify(data))
        //聊天框默认最底部

        //发送后关闭表情框
        $(".biaoqing-photo").toggle();
        //聊天框默认最底部
        chatBottom();
    })

});

// 发送图片
$("#inputImage").on("change", (res) => {
    var formData = new FormData();
    formData.append("file", $("#inputImage")[0].files[0]);
    formData.append("sendMemberId", sendMemberId)
    formData.append("acceptMemberId", acceptMemberId)
    $.ajax({
        url: '/uploadImg',
        type: 'post',
        data: formData,
        processData: false,
        contentType: false,
        success: function (msg) {
            showImg(msg.data);
        }
    });
})


//      显示图片
function showImg(images) {
    playSendMsgSound();
    $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
        "<div class=\"author-name\"><small class=\"chat-date\">" + sendTime() + "</small> </div> " +
        "<div class=\"right\"> <div class=\"chat-message\"><a href='" + images + "' id=\"showImg\" ><img src=" + images + "></div></a>" +
        "<div class=\"chat-avatars\"><img src=" + sendAvatarUrl + " alt=\"头像\" /></div> </div> </div>");
    //聊天框默认最底部
    chatBottom();
    imgbox();
}

window.CHAT = {
    socket: null,
    init: function () {
        //判断浏览器是否支持websocket
        if (window.WebSocket) {
            //创建websocket 对象
            CHAT.socket = new WebSocket("ws://127.0.0.1:8888/ws");
            CHAT.socket.onopen = function () {
                console.log("链接建立成功");
                var data = {
                    "memberId": sendMemberId,
                    "type": "REGISTER"
                };
                CHAT.socket.send(JSON.stringify(data));
                setInterval("heartbeat()", 60000);
            },
                CHAT.socket.close = function () {
                    console.log("链接关闭");
                },
                CHAT.socket.onerror = function () {
                    console.log("发生异常");
                },
                CHAT.socket.onmessage = function (e) {
                    let parse = JSON.parse(e.data);
                    console.log(parse);
                    switch (parse.data.type) {
                        case "REGISTER":
                            // 创建成功渲染好友页面
                            friendList(parse.data.friendList, parse.data.getUnreadMessage)
                            break;
                        case "SINGLE_SENDING":
                            friendList(parse.data.friendList, parse.data.getUnreadMessage);
                            // 一对一聊天
                            let msg = parse.data.chatMsg;
                            $("#chatBox-content-demo").append(acceptMsgList(msg))
                            chatBottom();
                            playReceiveMsgSound();
                            break;
                        case "NOT_LOGIN":
                            // 对方离线
                            console.log("对方离线")
                            break;
                        case "CHAT_LOG":
                            friendList(parse.data.friendList, parse.data.getUnreadMessage);
                            // 聊天记录
                            chatMsgLog(parse.data.chatMsgs);
                            // 重新渲染 imgbox方法
                            imgbox();
                            chatBottom();
                            break;
                        default:
                            console.log("不正确的类型！");
                    }

                }
        } else {
            console.log("您的浏览器不支持websocket协议");
        }
    },
    chat: function (msgContent) {
        //获取发送消息框中所输入内容
        //将客户输入的消息进行发送
        CHAT.socket.send(msgContent);
        playSendMsgSound();
    }
};

// 发送心跳
function heartbeat() {
    var data = {
        "type": "HEARTBEAT",
        "memberId": sendMemberId
    };
    CHAT.socket.send(JSON.stringify(data));
}

// 好友列表
function friendList(friendList, getUnreadMessage) {
    getUnreadMessageNum.innerHTML = '';
    buddyList.innerHTML = '';
    if (friendList.length > 0) {
        for (const item in friendList) {
            buddyList.innerHTML += list(friendList[item])
        }
        getUnreadMessageNum.innerHTML = getUnreadMessage > 0 ? getUnreadMessage : ''
    }
    //  没有消息
    notMsg();
    unreadMessageFriend();
}

// js获取当前的时分秒
function sendTime() {
    let myDate = new Date();
    let h = myDate.getHours(); // 获取当前小时数(0-23)
    let m = myDate.getMinutes(); // 获取当前分钟数(0-59)
    let s = myDate.getSeconds();// 获取当前秒数(0-59)
    return h + ':' + m + ':' + s;
}

//聊天框默认最底部
function chatBottom() {
    $(document).ready(function () {
        $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
    });
}

/**
 * 渲染聊天记录
 * @param acceptMsg
 * @param sendMsg
 */
function chatMsgLog(chatMsgs) {
    $("#chatBox-content-demo").html('')
    if (chatMsgs.length > 0) {
        for (const item in chatMsgs) {
            if (chatMsgs[item].acceptMemberId == sendMemberId) {
                $("#chatBox-content-demo").append(acceptMsgList(chatMsgs[item]))
            } else {
                $("#chatBox-content-demo").append(sendMsgList(chatMsgs[item]))
            }
        }
    }

}

//  接收消息记录
const acceptMsgList = ({createTime, msg}) => {
    return `<div class="clearfloat">
            <div class="author-name">
            <small class="chat-date">${createTime}</small>
            </div>
            <div class="left">
            <div class="chat-avatars">
                <img src=` + acceptAvatarUrl + ` alt="头像" />
            </div>
            <div class="chat-message">${msg}</div>
             </div>
             </div>`;
}
//  发送消息记录
const sendMsgList = ({createTime, msg}) => {
    return `<div class="clearfloat">
            <div class="author-name">
            <small class="chat-date">${createTime}</small>
            </div>
            <div class="right">
            <div class="chat-message">${msg} </div>
            <div class="chat-avatars"><img src=` + sendAvatarUrl + ` alt="头像" />
            </div>
             </div>
             </div>`;
}


// 进入聊天页面
function chatPage(userName, avatarUrl, memberId) {

    acceptAvatarUrl = avatarUrl;
    acceptMemberId = memberId;

    // 与双方聊天全部读取设置为true
    // 发送聊天记录请求

    $(".memberInfo").toggle();
    $(".chatBox-head-one").toggle();
    $(".chatBox-head-two").toggle();
    $(".chatBox-list").fadeToggle();
    $(".chatBox-kuang").fadeToggle();
    //传名字
    $(".ChatInfoName").text(userName);
    //传头像
    $(".ChatInfoHead>img").attr("src", avatarUrl);

    // 发送聊天记录请求
    var chatMsg = {
        "acceptMemberId": acceptMemberId,
        "sendMemberId": sendMemberId
    };
    var data = {
        "type": "CHAT_LOG",
        "chatMsg": chatMsg
    };
    // websocket 发送消息 查询全部聊天记录
    CHAT.socket.send(JSON.stringify(data));
    //聊天框默认最底部
    chatBottom();
}
